<!--
 * @Author: rouzi 924324407@qq.com
 * @Date: 2022-06-20 14:09:19
 * @LastEditors: rouzi 924324407@qq.com
 * @LastEditTime: 2022-06-20 14:40:05
 * @FilePath: \basice-exercise-code\手写reduce.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
     * @description: 手写reduce
     * @param {*} reducer 迭代函数
     * @param {*} currentValue 初始值
     * @return {*}
     */
    function myReduce(reducer, currentValue){
      let arr = this //调用数组
      let crr = currentValue || arr[0] // 累计初始值，currentValue为空 时用arr[0]
      let i = currentValue ? 0 : 1 // 循环初始值
      for (; i < arr.length; i++) {
        crr = reducer(crr,arr[i],i,arr)
      }
      return crr
    }
    Array.prototype.myReduce = myReduce

    // 测试
    let arr = [0,1,2,3,4]
    function reducer(acc, curr, index, src){
      return acc+curr
    }
    console.log(arr.reduce(reducer,10))
    console.log(arr.myReduce(reducer))

  </script>
</body>
</html>